package com.app.web.stomp
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.messaging.Message
import org.springframework.messaging.handler.annotation.DestinationVariable
import org.springframework.messaging.handler.annotation.MessageExceptionHandler
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.handler.annotation.SendTo
import org.springframework.messaging.simp.SimpMessageHeaderAccessor
import org.springframework.messaging.simp.SimpMessagingTemplate
import org.springframework.messaging.simp.annotation.SendToUser
import org.springframework.messaging.simp.annotation.SubscribeMapping
import org.springframework.stereotype.Controller

import java.security.Principal
/**
 * Created by three on 14-10-9.
 */
@CompileStatic
@TypeChecked
@Controller
class DemoController {

    @Autowired
    private SimpMessagingTemplate template;

//    @PostConstruct
    public void testSend(){
        new Thread(new Runnable() {
            @Override
            void run() {
                while (true) {
                    Thread.sleep(5000);
                    template.convertAndSend("/topic/system/msg", new Greeting("Hello, "+UUID.randomUUID().toString()));
                }
            }
        }).start();
    }

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        return new Greeting("Hello, " + message.getName() + "!");
    }

    /**
     * 对发送事件进行广播
     * 客户端发送 /app/echo
     * 客户端订阅 /echo/broadcast
     *
     * @param message
     * @param headerAccessor
     * @return
     */
    @MessageMapping("/echo")
    @SendTo("/echo/broadcast")
    public Greeting echo(EchoMessage message,SimpMessageHeaderAccessor headerAccessor) {
        Map<String, Object> sessionHeaders = SimpMessageHeaderAccessor.getSessionAttributes(headerAccessor.getSessionAttributes());
        println(message.getContent())
//        WebSocketMessageBrokerStats.
//        template.convertAndSendToUser("userid","",null);
        return new Greeting(message.getContent());
    }

    /**
     * 对发送事件，进行特定返回
     * 客户端发送 /app/joinRoom
     * 客户端订阅 /user/queue/send/joinRoom
     *
     * @param event
     * @param headerAccessor
     * @return
     */
    @MessageMapping("/send/{room}")
    @SendToUser(broadcast = false)
    public Greeting joinRoom(Event event,
                             @DestinationVariable("room") String room,
                             SimpMessageHeaderAccessor headerAccessor,
                             Message<Object> message) {
        Map<String, Object> sessionHeaders = SimpMessageHeaderAccessor.getSessionAttributes(headerAccessor.getSessionAttributes());
        String sessionId = headerAccessor.sessionId
        Principal user = headerAccessor.user
        template.convertAndSend("/topic/broadcast/"+room, new Greeting(sessionId + "发送消息："+event.content))

//        SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
//        headerAccessor.setSessionId(sessionId);
//        headerAccessor.setLeaveMutable(true);
//        ;
        template.convertAndSendToUser(sessionId,"/queue/recv/"+room,new Greeting(room+"给你的特定消息"), headerAccessor.getMessageHeaders())
        return new Greeting(sessionId + "发送成功")
    }

    /**
     * 订阅时间处理，基本只执行一下
     * 客户端订阅地址 /app/init/{room_xxx}
     * @return
     */
    @SubscribeMapping("/join/{room}")
    public Greeting getPortfolios(@DestinationVariable("room")String room) {
//        String user = principal.getName();
        return new Greeting("欢迎订阅： "+room)
    }

    /**
     * 异常处理
     *
     * @param ex
     * @return
     */
    @MessageExceptionHandler
    @SendToUser(value = "/queue/errors",broadcast = false)
    public String exHandler(Throwable ex) {
        return ex.getMessage();
    }
}
